<?php
/**
 * Created by Hera Portal.
 * User: Peter Fan(peter.fan@codelocks.hk)
 * Date: 2019/7/12 13:26
 */

namespace App\Library\Model;

use Illuminate\Contracts\Validation\Factory;
use Illuminate\Validation\Validator;

/**
 * Trait WithValidates
 * afterValidate(Validator $validate)
 * @package App\Library\Model
 */
trait WithValidates
{

    public $rules = [];
    protected $customMessages = [];
    protected $customAttributes = [];
//    protected function afterValidate($validator)
//    {
//
//
//    }

    /**
     * @param array|Validator $validator
     *
     * @return array
     * @throws \Illuminate\Validation\ValidationException
     */
    public function validateWith($validator)
    {
        if (is_array($validator)) {
            $validator = $this->getValidator($this->attributes, $validator);
        }
        if (method_exists($this, 'afterValidate')) {
            $validator->after(function ($validate) {
                call_user_func([$this, 'afterValidate'], $validate);
            });
        }
        return $validator->validate();
    }

    /**
     * @param array $data
     * @param array $rules
     * @param array $messages
     * @param array $customAttributes
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function getValidator($data, $rules, $messages = [], $customAttributes = [])
    {
        return $this->getValidationFactory()->make($data, $rules, $messages, $customAttributes);
    }

    /**
     * Get a validation factory instance.
     * @return Factory
     */
    protected function getValidationFactory()
    {
        return app(Factory::class);
    }


    /**
     * @param array $rules
     * @param array $messages
     * @param array $customAttributes
     *
     * @return array
     */
    public function validate($rules = null, $messages = null, $customAttributes = null)
    {
        $validator = $this->getValidator(
            $this->attributes,
            $rules ?: $this->rules ?? [],
            $messages ?: $this->customMessages,
            $customAttributes ?: $this->customAttributes
        );
        $validator->after(function ($validate) {
            if (method_exists($this, 'afterValidate')) {
                call_user_func([$this, 'afterValidate'], $validate);
            }
        });
        return $validator->validate();
    }

}
